import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './Registration.module.css'; // 使用CSS Modules导入样式

const Registration = () => {
  const [username, setUsername] = useState(''); // 保存用户名的状态
  const [password, setPassword] = useState(''); // 保存密码的状态
  const [confirmPassword, setConfirmPassword] = useState(''); // 保存确认密码的状态
  const navigate = useNavigate(); // 导航函数，用于页面跳转

  // 表单提交处理函数
  const handleSubmit = async (event) => {
    event.preventDefault(); // 阻止默认的表单提交行为

    // 简单的密码匹配验证
    if (password !== confirmPassword) {
      alert('密码不匹配，请检查您的输入。');
      console.log('Password mismatch:', { password, confirmPassword });
      return;
    }

    const formData = {
      username,
      password,
    };

    try {
      console.log('Sending registration data to /api/register:', formData);

      // 发送注册请求到第一个API
      const response1 = await fetch('http://localhost:8082/api/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData), // 将表单数据转换为 JSON 字符串
      });

      if (response1.ok) {
        console.log('Response from /api/register:', await response1.json());
        alert('注册成功！');
        // 注册成功后，导航到第二个注册页面，传递用户名作为 state
        navigate('/register2', { state: { username } });
      } else {
        console.error('Failed to register with /api/register:', response1.status, response1.statusText);
        alert('注册失败，请稍后再试。');
      }

      console.log('Sending registration data to /api/v1/users:', formData);

      // 发送注册请求到第二个API
      const response2 = await fetch('http://127.0.0.1:7860/api/v1/users/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': '*/*',
          'Cache-Control': 'no-cache', // 添加Cache-Control头
          'Connection': 'keep-alive',  // 添加Connection头
        },
        body: JSON.stringify(formData),
      });

      if (response2.ok) {
        console.log('Response from /api/v1/users:', await response2.json());
      } else {
        const errorData = await response2.json();
        console.error('Failed to register with /api/v1/users:', response2.status, response2.statusText);
        alert(`注册失败: ${errorData.message || 'Unknown error'}`);
      }
    } catch (error) {
      console.error('Error occurred during registration:', error);
      alert('请求失败，请稍后再试。');
    }
  };
  return (
    <div className={styles.registrationContainer}>
      <img src="/678.png" alt="智链iLink" className={styles.logo} />
      <h1 style={{color:'white',marginLeft:'120px',marginTop:'30px'}}>智链iLink</h1>
      <div className={styles.registrationLeft}>
        <h1 className={styles.tagline}>
          <span className={styles.highlight}>创新与班级管理</span>的信赖之选
        </h1>
        <img src="/yhtx_zc_show.png" alt="benefits and partners" className={styles.benefitsPartners} />
      </div>
      <div className={styles.registrationRight}>
        <h2 className={styles.formTitle}>填写信息</h2>
        <p className={styles.text1}>开启智链创新管理之路</p>
        <form className={styles.registrationForm} onSubmit={handleSubmit}>
          <input
            type="text"
            placeholder="请输入您的用户名"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            required
          />
          <input
            type="password"
            placeholder="请输入您的密码"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />
          <input
            type="password"
            placeholder="请再次输入您的密码"
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
            required
          />
          <button type="submit">注册试用</button>
        </form>
        <p className={styles.loginLink}>
          已有账号？ <a href="/login">去登录</a>
        </p>
      </div>
    </div>
  );
};

export default Registration;
